package com.ycsj.goldmedalnewconcept.student.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.activity.AnswerListDetailsActivity;
import com.ycsj.goldmedalnewconcept.common.activity.ErrorQuestionListActivity;
import com.ycsj.goldmedalnewconcept.common.activity.FollowReadDetailsActivity;
import com.ycsj.goldmedalnewconcept.common.activity.GammarTestActivity;
import com.ycsj.goldmedalnewconcept.common.activity.MicroClassroomActivity;
import com.ycsj.goldmedalnewconcept.common.activity.WordsPrepareActivity;
import com.ycsj.goldmedalnewconcept.common.activity.WordsTestActivity;
import com.ycsj.goldmedalnewconcept.common.activity.YuxiTestActivity;
import com.ycsj.goldmedalnewconcept.common.bean.UnitInfo;
import com.ycsj.goldmedalnewconcept.common.bean.UnitStateInfo;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.MilkUtils;
import com.ycsj.goldmedalnewconcept.common.util.PermissionUtil;
import com.ycsj.goldmedalnewconcept.common.util.UnitStateUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 预习复习
 */
public class YuXiAndFuXiAcitivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;
    @BindView(R.id.ll_chyx)
    LinearLayout llChyx;
    @BindView(R.id.ll_yxjc)
    LinearLayout llYxjc;
    @BindView(R.id.tv_error_yxjc)
    TextView tvErrorYxjc;
    @BindView(R.id.ll_chjc)
    LinearLayout llChjc;
    @BindView(R.id.tv_error_chjc)
    TextView tvErrorChjc;
    @BindView(R.id.tv_error_yfjc)
    TextView tvErrorYfjc;
    @BindView(R.id.ll_yfjc)
    LinearLayout llYfjc;
    @BindView(R.id.ll_wkt)
    LinearLayout llWkt;
    @BindView(R.id.ll_kwgd)
    LinearLayout llKwgd;

    //当前页面的单元信息对象和单元号
    private UnitInfo.LessonListBean info;

    //单元号
    private String unit;

    //根据不同模块拼接LessonId的前三位
    private String topThreeNum;

    //根据不同模块拼接LessId的后四位
    private String afterFourNum;

    //传递给下个页面的LessonId
    private String lessonId;

    //班级号
    private String classNum;

    //页面数据
    private UnitStateInfo.DataBean data;

    /**
     * 跳转到当前界面的方法
     *
     * @param info     当前界面的单元信息
     * @param unit     单元号
     * @param classNum 班级号
     */
    public static void goActivity(Context context, UnitInfo.LessonListBean info, String unit,
                                  String classNum) {
        Intent it = new Intent(context, YuXiAndFuXiAcitivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        bundle.putString("unit", unit);
        bundle.putString("classnum", classNum);
        it.putExtras(bundle);
        context.startActivity(it);

    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_yu_xi_and_fu_xi_acitivity;
    }

    @Override
    protected void init() {
        //初始化状态栏
        initStateBar();

        //获取intent
        initIntent();

        //根据单元号拼接LessonId
        initLessonId();

        //请求页面数据
        httpPageData();
    }


    /**
     * 获取Intent对象
     */
    private void initIntent() {
        info = (UnitInfo.LessonListBean) getIntent().getSerializableExtra("data");

        unit = getIntent().getStringExtra("unit");

        classNum = getIntent().getStringExtra("classnum");
        tvTitle.setText("Unit " + unit);

        rlLoading.setVisibility(View.VISIBLE);
        llContent.setVisibility(View.GONE);
    }


    /**
     * 根据单元号和模块拼接LessonId
     */
    private void initLessonId() {
        //返回的unit是1到72数字,根据拼接
        int unitNum = Integer.parseInt(unit);

        if (unitNum > 0 && unitNum <= 18) {

            applyMethod("10", "100", "10", unitNum);

        } else if (unitNum > 18 && unitNum <= 36) {

            applyMethod("20", "200", "20", unitNum);

        } else if (unitNum > 36 && unitNum <= 54) {

            applyMethod("30", "300", "30", unitNum);

        } else if (unitNum > 54 && unitNum <= 72) {

            applyMethod("40", "400", "40", unitNum);
        }
    }


    /**
     * 组装LessonId的后四位的方法
     *
     * @param levelUnit
     * @param threeNum
     * @param twoNum
     * @param unitNum
     */
    private void applyMethod(String levelUnit, String threeNum, String twoNum, int unitNum) {
        if (unitNum % 18 == 0) {
            //第36单元
            afterFourNum = levelUnit + "18";
        } else {
            //第1到17单元
            int res = unitNum % 18;
            if (res < 10) {
                afterFourNum = threeNum + res;
            } else {
                afterFourNum = twoNum + res;
            }
        }
    }

    /**
     * 请求页面数据
     */
    private void httpPageData() {
        UnitStateUtil.http(this, afterFourNum, classNum, new UnitStateUtil.onUnitStateListener() {
            @Override
            public void onSuccess(UnitStateInfo info) {
                rlLoading.setVisibility(View.GONE);
                if ("200".equals(info.state)) {
                    llContent.setVisibility(View.VISIBLE);

                    //设置页面数据
                    setPagetData(info);

                } else {
                    ToastUtils.showShort(BaseApplication.STATEERROE + info.state);
                }
            }

            @Override
            public void onError() {
                rlLoading.setVisibility(View.GONE);
                ToastUtils.showShort(BaseApplication.ERROR);
            }
        });
    }


    /**
     * 设置页面数据的方法
     *
     * @param info
     */
    private void setPagetData(UnitStateInfo info) {
        //分别获取预习检测,词汇检测,语法检测对应的错题数据
        data = info.data;

        if (data != null) {
            //词汇错题是否需要显示红色的标识,0灰1红
            String vocabularyNum = data.vocabulary_amount;
            if ("0".equals(vocabularyNum)) {
                //没有错题
                tvErrorChjc.setVisibility(View.INVISIBLE);
            } else {
                //有错题
                tvErrorChjc.setVisibility(View.VISIBLE);
                tvErrorChjc.setText(vocabularyNum);
                String vocabulary_isNew = data.vocabulary_isNew;
                if ("1".equals(vocabulary_isNew)) {
                    tvErrorChjc.setBackgroundResource(R.drawable.error_bg_select);
                } else {
                    tvErrorChjc.setBackgroundResource(R.drawable.error_bg_normal);
                }
            }

            //预习检测是否需要显示红色的标识,0灰1红
            String prepareNum = data.prepare_amount;
            if ("0".equals(prepareNum)) {
                //没有错题
                tvErrorYxjc.setVisibility(View.INVISIBLE);
            } else {
                //有错题
                tvErrorYxjc.setVisibility(View.VISIBLE);
                tvErrorYxjc.setText(prepareNum);
                String prepare_isNew = data.prepare_isNew;
                if ("1".equals(prepare_isNew)) {
                    tvErrorYxjc.setBackgroundResource(R.drawable.error_bg_select);
                } else {
                    tvErrorYxjc.setBackgroundResource(R.drawable.error_bg_normal);
                }
            }

            //语法检测是否需要显示红色的标识,0灰1红
            String grammarNum = data.grammar_amount;
            if ("0".equals(grammarNum)) {
                //没有错题
                tvErrorYfjc.setVisibility(View.INVISIBLE);
            } else {
                //有错题
                tvErrorYfjc.setVisibility(View.VISIBLE);
                tvErrorYfjc.setText(grammarNum);
                String grammar_isNew = data.grammar_isNew;
                if ("1".equals(grammar_isNew)) {
                    tvErrorYfjc.setBackgroundResource(R.drawable.error_bg_select);
                } else {
                    tvErrorYfjc.setBackgroundResource(R.drawable.error_bg_normal);
                }
            }
        }
    }

    /**
     * 点击错题集后请求服务器同步错题集状态
     */
    private void httpSysErrorState(final String moduleid) {
        UnitStateUtil.httpState(this, afterFourNum, classNum, moduleid, new UnitStateUtil.onSycStateListener() {
            @Override
            public void onSuccess() {
                //成功后同步页面状态
                if ("1".equals(moduleid)) {
                    //词汇检测
                    data.vocabulary_isNew = "0";
                    tvErrorChjc.setBackgroundResource(R.drawable.error_bg_normal);
                } else if ("2".equals(moduleid)) {
                    //预习检测
                    data.prepare_isNew = "0";
                    tvErrorYxjc.setBackgroundResource(R.drawable.error_bg_normal);
                } else if ("4".equals(moduleid)) {
                    //语法检测
                    data.grammar_isNew = "0";
                    tvErrorYfjc.setBackgroundResource(R.drawable.error_bg_normal);
                }
            }
        });
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.ll_chyx, R.id.ll_yxjc, R.id.tv_error_yxjc, R.id.ll_chjc, R.id.tv_error_chjc, R.id.tv_error_yfjc, R.id.ll_yfjc, R.id.ll_wkt, R.id.ll_kwgd})
    public void onViewClicked(View view) {
        if (!isDoubleClick(view)) {


            switch (view.getId()) {
                case R.id.iv_back:
                    //返回
                    finish();
                    break;
                case R.id.ll_chyx:
                    //词汇预习
                    topThreeNum = "200";
                    lessonId = topThreeNum + afterFourNum;
                    WordsPrepareActivity.goActivity(this, lessonId, unit);
                    break;

                case R.id.ll_yxjc:
                    //预习检测
                    topThreeNum = "200";
                    lessonId = topThreeNum + afterFourNum;
                    YuxiTestActivity.goActivity(this, lessonId, classNum);
                    break;

                case R.id.ll_chjc:
                    //词汇检测
                    topThreeNum = "100";
                    lessonId = topThreeNum + afterFourNum;
                    WordsTestActivity.goActivity(this, lessonId, classNum);
                    break;

                case R.id.ll_yfjc:
                    //语法检测
                    topThreeNum = "400";
                    lessonId = topThreeNum + afterFourNum;
                    GammarTestActivity.goActivity(this, lessonId, classNum);

                    break;

                case R.id.tv_error_yxjc:
                    //预习检测的错题
                    if ("1".equals(data.prepare_isNew)) {
                        httpSysErrorState("2");
                    }
                    lessonId = afterFourNum;
                    //跳转H5
                    ErrorQuestionListActivity.goActivity(this, lessonId, classNum, "2");
                    break;

                case R.id.tv_error_chjc:
                    //词汇检测的错题
                    if ("1".equals(data.vocabulary_isNew)) {
                        httpSysErrorState("1");
                    }
                    lessonId = afterFourNum;
                    //跳转H5
                    ErrorQuestionListActivity.goActivity(this, lessonId, classNum, "1");

                    break;
                case R.id.tv_error_yfjc:
                    //语法检测的错题
                    if ("1".equals(data.grammar_isNew)) {
                        httpSysErrorState("4");
                    }
                    lessonId = afterFourNum;
                    //跳转H5
                    ErrorQuestionListActivity.goActivity(this, lessonId, classNum, "4");

                    break;

                case R.id.ll_wkt:
                    //微课堂
                    topThreeNum = "300";
                    lessonId = topThreeNum + afterFourNum;

                    if ("0".equals(AccountUtils.getRole(this))) {
                        //只有学生端时调用生成牛奶的接口
                        MilkUtils.getMilk(this, AccountUtils.getTeacher(this), AccountUtils.getClassNum(this)
                                , "3", lessonId, "5", "");
                    }
                    //跳转微课堂
                    MicroClassroomActivity.goActivity(this, info, lessonId);

                    break;
                case R.id.ll_kwgd:
                    //课文跟读
                    topThreeNum = "900";
                    lessonId = topThreeNum + afterFourNum;

                    if (Build.VERSION.SDK_INT >= 23) {
                        if (PermissionUtil.checkIsPermission(YuXiAndFuXiAcitivity.this, PermissionUtil.PERMISSIONS_RECORD_AUDIO)) {
                            //如果没有进行过课文跟读
                            if ("0".equals(info.getRepeat_done())) {
                                FollowReadDetailsActivity.goActivity(this, lessonId, unit);
                            } else {
                                //已经进行过课文跟读,跳转到课文跟读的列表
                                AnswerListDetailsActivity.goActivity(this, lessonId, "1");
                            }
                        } else {
                            PermissionUtil.checkAndRequestPermissions(YuXiAndFuXiAcitivity.this, PermissionUtil.PERMISSIONS_RECORD_AUDIO);

                        }

                    } else {
                        if ("0".equals(info.getRepeat_done())) {
                            FollowReadDetailsActivity.goActivity(this, lessonId, unit);
                        } else {
                            //已经进行过课文跟读,跳转到课文跟读的列表
                            AnswerListDetailsActivity.goActivity(this, lessonId, "1");
                        }
                    }

                    break;
            }
        }
    }

    /**
     * 申请权限的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDenin = false;

        LogUtils.iTag("test", grantResults);

        if (requestCode == PermissionUtil.REQUEST_CODE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDenin = true;

                    break;
                }
            }
            if (hasPermissionDenin) {
                ToastUtils.showShort("未同意录音权限将无法使用相关功能");
            } else {
                //如果没有进行过课文跟读
                if ("0".equals(info.getRepeat_done())) {
                    FollowReadDetailsActivity.goActivity(this, lessonId, unit);
                } else {
                    //已经进行过课文跟读,跳转到课文跟读的列表
                    AnswerListDetailsActivity.goActivity(this, lessonId, "1");
                }
            }
        }
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo) {
            if (FollowReadDetailsActivity.FINISH == busInfo.type) {
                //同步课文跟读状态
                if (null != info && !"1".equals(info.getRepeat_done())) {
                    info.setRepeat_done("1");
                }
            }
        }
    }
}
